package org.xiaoleng.cdm.convertors;

import org.springframework.util.StringUtils;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class MysqlFieldConvertor {

    private static Map<String, Function<String, Object>> mapping = new HashMap<>();

    static {
        // 整数类型
        mapping.put("TINYINT", Byte::valueOf);
        mapping.put("SMALLINT", Short::valueOf);
        mapping.put("MEDIUMINT", Integer::valueOf);
        mapping.put("BIGINT", Long::valueOf);

        // 浮点类型
        mapping.put("FLOAT", Float::valueOf);
        mapping.put("DOUBLE", Double::valueOf);

        // 日期和时间类型
        mapping.put("DATE", Date::valueOf);
        mapping.put("TIME", Time::valueOf);
        mapping.put("TIMESTAMP", Timestamp::valueOf);
        mapping.put("YEAR", Integer::valueOf);

        // 字符串类型
        mapping.put("CHAR", String::valueOf);
        mapping.put("VARCHAR", String::valueOf);
        mapping.put("TINYTEXT", String::valueOf);
        mapping.put("TEXT", String::valueOf);
        mapping.put("MEDIUMTEXT", String::valueOf);
        mapping.put("LONGTEXT", String::valueOf);
        mapping.put("MEDIUMBLOB", String::valueOf);
        mapping.put("LONGBLOB", String::valueOf);

    }

    public static Object convert(String type, String value) {
        if (!StringUtils.isEmpty(type) && !StringUtils.isEmpty(value) && mapping.containsKey(type)) {
            return mapping.get(type).apply(value);
        }
        return null;
    }
}
